<script lang="js" setup>
import {onMounted, ref} from 'vue';
import {Pagination, Autoplay} from 'swiper/modules';
import { ElMessageBox } from 'element-plus';
import {
  ArrowLeftOutlined,
  HeartOutlined,
  ShareAltOutlined,
  HomeOutlined,
  CompassOutlined,
  ColumnHeightOutlined,
  KeyOutlined,
  CalendarOutlined,
  BankOutlined,
  DownOutlined,
  UpOutlined,
  MessageOutlined,
  PhoneOutlined,
  TransactionOutlined,
  CheckCircleOutlined,
  FileDoneOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons-vue';

import axios from "axios";
import {message} from "ant-design-vue";
import {useRouter} from 'vue-router'
import ChatPopup from '../chat/chatOne.vue'
import {jwtDecode} from "jwt-decode";

const swiperModules = [Pagination, Autoplay];
//是否显示完整描述
const showFullDesc = ref(false);
const houseId = sessionStorage.getItem("houseId");
const house = ref();
const router = useRouter();
const userID = ref('');
const houseImages = ref([]);

//配套设施
const facilities = ref([]);

//标签
const labels = ref([]);

//用户信息
const userInfo = ref([]);

const token = localStorage.getItem("access-token");

console.log(token)

const showChat = ref(false)
const favoriteStatus = ref(false);

const swiperInstance = ref(null);

const onSwiper = (swiper) => {
  swiperInstance.value = swiper;
};

const prevSlide = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slidePrev();
  }
};

const nextSlide = () => {
  if (swiperInstance.value) {
    swiperInstance.value.slideNext();
  }
};

const setHouse = async () => {
  try {
    const response = await axios.get(`${window.link}/house/${houseId}`, {
      headers: {
        "access-token": `${token}`, // 使用标准头代替自定义头
      },
    });
    if (response.data.code === 200) {
      house.value = response.data.data.house;
      labels.value = response.data.data.houseLabels;
      facilities.value = response.data.data.facilities;
      userInfo.value = response.data.data.userInfo;
      houseImages.value = response.data.data.graphs;
      console.log(house.value.title);

      sessionStorage.setItem("ownerId", house.value.ownerId);
      sessionStorage.setItem("houseId", house.value.id);
      sessionStorage.setItem("houseTitle", house.value.title);
      sessionStorage.setItem("houseRent", house.value.rent);
      sessionStorage.setItem("houseArea", `${house.value.province}/${house.value.city}/${house.value.district}`);
      sessionStorage.setItem("ownerPhone", userInfo.value.phone);
      sessionStorage.setItem("ownerName", userInfo.value.name)
      console.log(response)
    } else {
      console.log(response)
      if (response.data.code === 601 || response.data.code === 602 || response.data.code === 201) {
        await router.push("/user/login/loginByAccount")
      }
      message.error("登录错误")
    }
  } catch (error) {
    console.error("获取详细信息失败", error)
  }
}

const back = () => {
  router.push('/');
}


const setFavorite = async () => {
  try {
    const response = await axios.get(`${window.link}/user/favorite/status/${houseId}`, {
      headers: {
        "access-token": token
      }
    });
    if (response.data.code === 200) {
      favoriteStatus.value = response.data.data;
      // console.log(favoriteStatus.value)
    } else {
      message.error("收藏状态获取失败")
    }
  } catch (error) {
    console.error("收藏状态获取失败", error);
    message.error("收藏状态获取失败");
  }
}

setHouse();
setFavorite();
const handleFavorite = async () => {
  if (favoriteStatus.value) {
    try {
      const response = await axios.delete(`${window.link}/user/favorite/${houseId}`, {
        headers: {
          "access-token": `${token}`
        }
      });
      if (response.data.code === 200) {
        message.success("取消收藏成功");
        favoriteStatus.value = false;
      } else {
        message.error("取消收藏失败");
      }
    } catch (error) {
      console.error("取消收藏失败", error);
      message.error("取消收藏失败");
    }
  } else {
    try {
      const response = await axios.post(`${window.link}/user/favorite/${houseId}`, {}, {
        headers: {
          "access-token": localStorage.getItem('access-token')
        }
      });
      console.log(response)
      if (response.data.code === 200) {
        message.success("收藏成功");
        favoriteStatus.value = true;
      } else {
        message.error("收藏失败");
      }
    } catch (error) {
      console.error("收藏失败", error);
      message.error("收藏失败");
    }
  }
}

const status = () => {
  console.log(userID.value)
  console.log(sessionStorage.getItem("ownerId"))
  return userID.value == sessionStorage.getItem("ownerId");
}

const goToSeetime = () => {
  if (status()) {
    message.error("您自己作为房东，不能使用该功能")
    return
  }
  router.push("/seetimeHouse");
}

const goToChat = () => {
  if (status()) {
    message.error("您自己作为房东，不能使用该功能")
    return
  }
  showChat.value = true
}
const goToContract = () => {
  if (status()) {
    message.error("您自己作为房东，不能使用该功能")
    return
  }
  router.push("/contract");
}
const share = () => {
  // 获取当前页面的地址
  const currentUrl = window.location.href;
  // 将地址复制到剪切板
  navigator.clipboard.writeText(currentUrl).then(() => {
    message.success("URL已成功复制到剪切板！");
  }).catch(err => {
    message.error("复制失败: ", err);
  });
}

const call = () => {
  alert("电话为：" + userInfo.value.phone)
}
onMounted(() => {
  const token = localStorage.getItem("access-token");
  try {
    const decodedToken = jwtDecode(token);
    console.log(decodedToken)
    userID.value = decodedToken.userId; // 确保后端 token 中包含 role 字段
  } catch (error) {
    console.error('Token 解析失败:', error);
    message.error('登录信息解析失败');
  }
});

const currentIndex = ref(0)
const videoExtensions = ['mp4', 'webm', 'ogg']
const isVideo = (url) => {
  const extension = url.split('.').pop().toLowerCase()
  return videoExtensions.includes(extension)
}

const next = () => {
  currentIndex.value = (currentIndex.value + 1) % houseImages.value.length
}

const prev = () => {
  currentIndex.value = currentIndex.value === 0
      ? houseImages.value.length - 1
      : currentIndex.value - 1
}

const goToSlide = (index) => {
  currentIndex.value = index
}


</script>
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <div class="fixed top-0 left-0 right-0 z-50 bg-white shadow-sm">
      <div class="max-w-7xl mx-auto px-4 h-14 flex items-center justify-between">
        <div class="flex items-center">
          <a-button type="text" class="!rounded-button">
            <home-outlined class="text-xl" @click="back"/>
          </a-button>
        </div>
        <div class="flex items-center space-x-4">
          <a-button type="text" class="!rounded-button" @click="handleFavorite">
            <heart-outlined class="text-xl" :class="{'text-red-500': favoriteStatus}"/>
          </a-button>
          <a-button type="text" class="!rounded-button" @click="share">
            <share-alt-outlined class="text-xl"/>
          </a-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <!-- 图片演示 -->
    <div class="max-w-7xl mx-auto pt-14">
      <div class="flex gap-4 w-full">
        <div class="flex-1 relative h-[480px]">
          <div class="carousel">
            <!-- 轮播图容器 -->
            <div class="carousel-container" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
              <div v-for="item in houseImages" :key="item.id" class="carousel-item">
                <img v-if="!isVideo(item.url)" :src="item.url" :alt="`slide-${item.id}`">
                <video
                    v-else
                    :src="item.url"
                    controls
                    @play="pauseAutoPlay"
                    @pause="resumeAutoPlay"
                ></video>
              </div>
            </div>

            <!-- 切换按钮 -->
            <button class="prev" @click="prev">←</button>
            <button class="next" @click="next">→</button>

            <!-- 指示器 -->
            <div class="indicators">
      <span
          v-for="(item, index) in houseImages"
          :key="item.id"
          :class="{ active: currentIndex === index }"
          @click="goToSlide(index)"
      ></span>
            </div>
          </div>
        </div>

        <!-- 右侧用户信息卡片 -->
        <div class="w-[300px] bg-white p-6 h-[480px] flex flex-col">
          <!-- 房东信息 -->
          <div class="flex flex-col items-center border-b pb-6">
            <a-avatar :size="80" :src="userInfo.avatar"/>
            <div class="mt-4 text-center">
              <div class="flex items-center justify-center">
                <span class="text-lg font-bold">{{ userInfo.nickName }}</span>
                <a-tag color="blue" class="ml-2">已认证</a-tag>
              </div>
              <div class="text-gray-500 mt-2">
                <span>房源数 {{ userInfo.releaseNum }}</span>
                <span class="mx-2">·</span>
                <span>已成交 {{ userInfo.contractNum }}</span>
              </div>
            </div>
          </div>

          <!-- 联系方式 -->
          <div class="grid grid-cols-2 gap-3 mt-6">
            <a-button
                type="primary"
                class="contact-btn"
                @click="goToChat"
            >
              <div class="flex flex-col items-center">
                <message-outlined class="text-xl mb-1"/>
                <span class="text-sm">在线咨询</span>
              </div>
            </a-button>

            <a-button
                type="primary"
                class="contact-btn"
                @click="call"
            >
              <div class="flex flex-col items-center">
                <phone-outlined class="text-xl mb-1"/>
                <span class="text-sm">电话联系</span>
              </div>
            </a-button>

            <a-button
                type="primary"
                class="contact-btn"
                @click="goToContract"
            >
              <div class="flex flex-col items-center">
                <file-done-outlined class="text-xl mb-1"/>
                <span class="text-sm">在线签约</span>
              </div>
            </a-button>

            <a-button
                type="primary"
                class="contact-btn"
                @click="goToSeetime"
            >
              <div class="flex flex-col items-center">
                <calendar-outlined class="text-xl mb-1"/>
                <span class="text-sm">预约看房</span>
              </div>
            </a-button>
          </div>

        </div>
      </div>

      <!-- 核心信息 -->
      <div class="bg-white mt-4 p-6">
        <h1 class="text-2xl font-bold mb-4"><span>{{ house.title }}</span></h1>
        <div class="flex items-baseline mb-4">
          <span class="text-3xl font-bold text-red-500">{{ house.rent }}</span>
          <span class="text-gray-500 ml-2">元/月</span>
        </div>
        <div class="inline-flex gap-2 mb-4 layui-margin-2" v-for="item in labels" :key="item.id">
          <a-tag color="blue">{{ item.name }}</a-tag>
        </div>
      </div>

      <!-- 房屋参数 -->
      <div class="bg-white mt-4 p-6">
        <h2 class="text-xl font-bold mb-4">房屋参数</h2>
        <div class="grid grid-cols-3 gap-4">
          <div class="flex items-center">
            <home-outlined class="text-blue-500 mr-2"/>
            <span>建筑面积：{{ house.area }}㎡</span>
          </div>
          <div class="flex items-center">
            <compass-outlined class="text-blue-500 mr-2"/>
            <span>朝向：{{ house.orientation }}</span>
          </div>
          <div class="flex items-center">
            <column-height-outlined class="text-blue-500 mr-2"/>
            <span>楼层：{{ house.floor }}层</span>
          </div>
          <div class="flex items-center">
            <transaction-outlined class="text-blue-500 mr-2"/>
            <span>装修：{{ house.decoration }}</span>
          </div>
          <div class="flex items-center">
            <calendar-outlined class="text-blue-500 mr-2"/>
            <span>户型：{{ house.layout }}</span>
          </div>
          <div class="flex items-center">
            <bank-outlined class="text-blue-500 mr-2"/>
            <span>租约方式：{{ house.rentalMethod }}</span>
          </div>
        </div>
      </div>

      <!-- 配套设施 -->
      <div class="bg-white mt-4 p-6">
        <h2 class="text-xl font-bold mb-4">配套设施</h2>
        <div class="grid grid-cols-4 gap-4">
          <div v-for="facility in facilities" :key="facility.id"
               class="flex flex-col items-center">
            <img :src="facility.icon" class="w-8 h-8 object-cover rounded-lg mb-2"/>
            <span>{{facility.name}}</span>
          </div>
        </div>
      </div>

      <!-- 房源描述 -->
      <div class="bg-white mt-4 p-6">
        <h2 class="text-xl font-bold mb-4">房源描述</h2>
        <div :class="{'max-h-32': !showFullDesc}" class="relative overflow-hidden">
          <p class="text-gray-600 leading-relaxed">
            {{ house.description }}
          </p>
          <div v-if="!showFullDesc"
               class="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-white to-transparent"></div>
        </div>
        <div class="text-center mt-4">
          <a-button type="link" @click="showFullDesc = !showFullDesc" class="!rounded-button">
            {{ showFullDesc ? '收起' : '展开更多' }}
            <down-outlined v-if="!showFullDesc"/>
            <up-outlined v-else/>
          </a-button>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加聊天弹窗 -->
  <ChatPopup
      v-if="showChat"
  />
</template>


<style scoped>
.swiper {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.swiper-slide {
  width: 100% !important;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 确保图片和视频完全覆盖滑块区域 */
.swiper-slide img,
.swiper-slide video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.ant-tag) {
  margin-right: 0;
}

/* 添加阴影效果 */
.bg-white {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.contact-btn {
  height: 64px !important;
  padding: 8px !important;
  display: flex !important;
  align-items: center;
  justify-content: center;
}

.swiper-container {
  width: 100%;
  height: 100%;
}

:deep(.ant-btn-primary) {
  background-color: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background-color: #40a9ff;
}

.nav-btn {
  background-color: rgba(255, 255, 255, 0.8) !important;
  border: none !important;
  width: 40px;
  height: 40px;
  border-radius: 50% !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover {
  background-color: rgba(255, 255, 255, 0.9) !important;
}

.carousel {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.carousel-container {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
}

.carousel-item {
  flex: 0 0 100%;
  width: 100%;
  height: 100%;
}

.carousel-item img,
.carousel-item video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.prev, .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(255, 255, 255, 0.8);
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  cursor: pointer;
  z-index: 10;
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}

.indicators {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.indicators span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
}

.indicators span.active {
  background: white;
}
</style>


